<?php

declare(strict_types=1);

namespace Service\UserService;

use App\Model\BbcModel\Config;
use App\Model\BbcModel\ConfigChannel;
use App\Model\BbcModel\Decorate;
use App\Model\BbcModel\DecorateDetail;
use App\Model\BbcModel\DecorateTab;
use App\Model\BbcModel\LedgerConfig;
use App\Model\BbcModel\MnCommission;
use App\Model\BbcModel\MnStoreCheck;
use App\Model\BbcModel\MnStoreGoods;
use App\Model\BbcModel\Mnuser;
use App\Model\BbcModel\Order;
use App\Model\BbcModel\SpecialtopicGoods;
use App\Model\BbcModel\StoreVip;
use App\Model\BbcModel\StoreVisit;
use App\Model\BbcModel\ViceStore;
use Hyperf\DbConnection\Db;
use PhpParser\Node\Stmt\Nop;
use Service\BaseService;
use Service\ChannelService\ChannelWxService;
use Service\Code\Normal;
use Service\HelperService\Str;

/**
 * 店铺用户中心服务
 * @author chenshubo
 */

class MnUserService extends BaseService
{
    const TYPE_O2O      = 2; //线上分销2:o2o
    const TYPE_QZ       = 3; //前置仓店
    const TYPE_DEFAULT  = 1; //默认类型

    /**
     * 获取店铺用户信息
     * @param int $mn_sid
     */
    public static function getMnUserInfoByMnSid(int $mn_sid)
    {
        return Mnuser::instance()->info(['id' => $mn_sid]);
    }

    /**
     * 获取分享店铺条件
     * @param int $mn_sid
     */
    public function memberShareGetWhere($mn_sid)
    {
        $mnuser = Mnuser::instance()->info(['id' => $mn_sid]);
        if ($mnuser['member_share'] == 1) {
            $mnsids = Mnuser::instance()->where([
                'pid' => $mnuser['pid'],
                'member_share' => 1,
                'status' => 1,
                'new_store' => 1
            ])->pluck('id');
            return ['mn_sid', 'in', $mnsids];
        }
        return ['mn_sid', '=', $mn_sid];
    }

    /**
     * 小店首页
     * @param int $mnid
     * @param int $cid
     * @param int $mn_sid
     * @param int $mid
     * @return array
     */
    public function storeIndex(int $mnid, int $cid, int $mn_sid, int $mid): array
    {
        $checkResult = $this->checkStore($mnid, $cid, $mn_sid, $mid);
        if ($checkResult['code'] != Normal::SUC) {
            return $checkResult;
        }
        $info = $checkResult['data'];
        //提现金额
        $qStore = Config::instance()->info(['code' => 'wx_mnapp']);
        $qStoreConfig = json_decode($qStore['value'], true);
        $info['withdraw_limit'] = $qStoreConfig['withdraw_limit'] ?? 0;
        //appId
        $mnConfig = ChannelWxService::instance()->getMnApp($cid, $mnid);
        $info['store_app_id'] = $mnConfig['data']['value']['appid'] ?? '';
        //订单数据
        $today = strtotime(date('Ymd'));
        $todayOrders = Order::instance()->lists([
            ['pay_status', '=', 1],
            ['mn_sid', '=', $info['id']],
            ['status', '>', 0],
            ['cd', '>', $today],
            '_order_' => 'id desc',
            '_fields_' => 'id,price_order,distribute_money'
        ]);
        $info['today_sell'] = round(array_sum(array_column($todayOrders, 'price_order')), 2);
        $info['today_number'] = count($todayOrders);
        $info['today_distribute'] = round(array_sum(array_column($todayOrders, 'distribute_money')), 2);
        $info['all_number'] = Order::instance()->countNum([
            ['pay_status', '=', 1],
            ['mn_sid', '=', $info['id']],
            ['status', '>', 0],
        ]);
        $orderPermit = 0;
        $permit = ConfigChannel::instance()->info(['cid' => $cid, 'code' => 'btb_buy']);
        if (!empty($permit) && !empty($permit['value'])) {
            $permitValue = json_decode($permit['value'], true);
            $orderPermit = $permitValue['price_commission'] ?? 0;
        }
        if ($orderPermit == 1) {
            $midNum = Order::instance()->countNum(
                ['pay_status', '=', 1],
                ['mid', '=', $info['mid']],
                ['status', '>', 0],
            );
            $info['all_number'] += $midNum;
        }

        $info['all_distribute'] = round($info['wallet_accumulate_income'] + $info['frozen_income'], 2);
        $orderCounts = Order::instance()->where('mn_sid', $info['id'])->where('mnid', 4)
            ->whereIn('status', [20, 30, 40, 50])
            ->groupBy('status')->select([
                'status',
                Db::raw('count(id) order_count')
            ])->get()->toArray();
        $orderCountMap = array_column($orderCounts, 'order_count', 'status');
        $info['order']['waitSend'] = $orderCountMap[20] ?? 0; //待发货订单
        $info['order']['waitReceive'] = $orderCountMap[30] ?? 0; //待收货订单
        $info['order']['finish'] = ($orderCountMap[40] ?? 0) + ($orderCountMap[50] ?? 0); //已完成订单
        $info['today_visit'] = StoreVisit::instance()->where(['mn_sid' => $info['id'], 'date' => date('Y-m-d', time())])->groupBy("mid,date")->count();
        $info['total_visit'] = StoreVisit::instance()->where(['mn_sid' => $info['id']])->groupBy("mid,date")->count();
        $config = ConfigChannel::instance()->info(['code' => 'settle_bill_day', 'cid' => $cid]);
        $day = 0;
        if (!empty($config)) {
            $value = json_decode($config['value'], true);
            $day = $value['day'] ?? MnCommission::instance()->day;
        }
        $info['frozen_day'] = intval($day);
        return Normal::returnCode(Normal::SUC, '获取成功', $info);
    }

    /**
     * 
     * @param [type] $mnid
     * @param [type] $cid
     * @param [type] $mn_sid
     * @param [type] $mid
     * @return array
     */
    public function checkStore($mnid, $cid, $mn_sid, $mid)
    {
        if ($mnid == 2) {
            if (empty($mid)) {
                return Normal::returnCode(Normal::FAIL, '请先登录');
            }
            $store = Mnuser::instance()->info([
                'mid' => $mid,
                'status' => 1,
                'check_status' => 1,
                'new_store' => 1,
                'is_pay' => 1,
                'pid' => $cid
            ]);
            if (empty($store)) {
                return Normal::returnCode(Normal::FAIL, '请先开通小店');
            }
            if ($mn_sid = 0) {
                return Normal::returnCode(Normal::SUC, 'ok', $store);
            }
            if ($mn_sid == $store['id']) {
                return Normal::returnCode(Normal::SUC, 'ok', $store);
            }
            $checkRelation = ViceStore::instance()->checkRelation([
                'main_mn_sid' => $store['id'], 'vice_mn_sid' => $mn_sid, 'cid' => $cid
            ]);
            if (!$checkRelation) {
                return Normal::returnCode(Normal::FAIL, '该店铺不是你的关联店铺');
            }
            $mnUserInfo = Mnuser::instance()->info([
                'id' => $mn_sid,
                'status' => 1,
                'check_status' => 1,
                'new_store' => 1,
                'is_pay' => 1,
                'pid' => $cid
            ]);
            if (empty($mnUserInfo)) {
                return Normal::returnCode(Normal::FAIL, '关联的小店不存在');
            }
            return Normal::returnCode(Normal::SUC, 'ok', $mnUserInfo);
        }

        //C端小程序
        if (empty($mn_sid)) {
            return Normal::returnCode(Normal::FAIL, '小店不存在');
        }
        $mnUserInfo = Mnuser::instance()->info([
            'id' => $mn_sid,
            'status' => 1,
            'check_status' => 1,
            'new_store' => 1,
            'is_pay' => 1,
            'pid' => $cid
        ]);
        if (empty($mnUserInfo)) {
            return Normal::returnCode(Normal::FAIL, '小店不存在');
        }
        return Normal::returnCode(Normal::SUC, 'ok', $mnUserInfo);
    }

    /**
     * 线下门店列表
     * @param int $mnid
     * @param int $cid
     * @param int $mn_sid
     * @param int $page
     * @param int $limit
     * @param [type] $mid
     * @return array
     */
    public function shopList(int $mnid, int $cid, int $mn_sid, int $page, int $limit, $mid): array
    {
        $start = ($page - 1) * $limit;
        $where = [
            ['pid', '=', $cid],
            ['status', '=', 1],
            ['type', '=', 2],
            ['member_share', '=', 1],
            ['id', '<>', $mn_sid],
            '_fields_' => "id as mn_sid,store_name,lat,lng,store_address,img,'9:00-21:00' as shopping_time",
            '_limit_' => [$start, $limit],
            '_order_' => 'id desc'
        ];
        $list = Mnuser::instance()->lists($where);
        $current = Mnuser::instance()->info([
            '_fields_' => 'id as mn_sid,store_name,lat,lng,store_address,img,\'9:00-21:00\' as shopping_time',
            'id' => $mn_sid
        ]);
        return Normal::returnCode(Normal::SUC, '请求成功', [
            'now' => $current,
            'list' => $list
        ]);
    }

    /**
     * 申请小店资料变更
     * @param int $mnid
     * @param string $store_name
     * @param string $img
     * @param int $cid
     * @param int $mn_sid
     */
    public function applyCheck(int $mnid, string $store_name, string $img, int $cid, int $mn_sid, int $mid)
    {
        if (empty($mid)) {
            return Normal::returnCode(Normal::FAIL, '请先登录');
        }
        if (empty($store_name) && empty($img)) {
            return Normal::returnCode(Normal::FAIL, '店铺名字和图片请至少提交一项变更');
        }

        $flag =  Str::has_special_char($store_name);
        if ($flag) {
            return Normal::returnCode(Normal::FAIL, '店铺名字不可含有特殊表情');
        }
        $checkResult = MnUserService::instance()->checkStore($mnid, $cid, $mn_sid, $mid);
        if ($checkResult['code'] != Normal::SUC) {
            return $checkResult;
        }
        $info = $checkResult['data'];
        $isExist = MnStoreCheck::instance()->info(['mnid' => $mnid, 'mid' => $mid, 'status' => 0, 'mn_sid' => $info['id']]);
        if ($isExist) {
            return Normal::returnCode(Normal::FAIL, '您已经提交了审核资料，还在审核中');
        }
        $insertResult = MnStoreCheck::instance()->add([
            'store_name' => $store_name,
            'img' => $img,
            'cd' => time(),
            'check_time' => time(),
            'status' => 1,
            'mid' => $mid,
            'mnid' => $mnid,
            'mn_sid' => $info['id'],
            'cid' => $cid
        ]);
        if (!$insertResult) {
            return Normal::returnCode(Normal::FAIL, '修改失败');
        }
        $editData = [
            'md' => time(),
        ];
        if (!empty($store_name)) {
            $editData['store_name'] = $store_name;
        }
        if (!empty($img)) {
            $editData['img'] = $img;
        }
        Mnuser::instance()->edit(['id' => $info['id']], $editData);
        return Normal::returnCode(Normal::SUC, '修改成功');
    }

    /**
     * 小店资料
     * @param int $mnid
     * @param int $mn_sid
     * @param int $cid
     * @param int $mid
     */
    public function getInfo(int $mnid, int $mn_sid, int $cid, int $mid)
    {
        $checkResult = MnUserService::instance()->checkStore($mnid, $cid, $mn_sid, $mid);
        if ($checkResult['code'] != Normal::SUC) {
            return $checkResult;
        }
        $info = $checkResult['data'];
        $data['info'] = [
            'store_name' => $info['store_name'],
            'img' => $info['img'],
            'store_id' => $info['id'],
            'adv_temp' => $info['adv_temp'],
            'link_mobile' => $info['link_mobile'] ?? $info['account'],
            'link_man' => $info['link_man'],
            'qrcode' => $info['qrcode'],
            'type' => $info['type'],
            'member_share' => $info['member_share'],
            'channel_type' => $info['channel_type'],
            'lat' => $info['lat'],
            'lng' => $info['lng'],
            'auto_up' => $info['auto_up'],
            'store_address' => $info['store_address'],
            'show_points' => $info['show_points'] == 2 ? 0 : 1,
            'show_name' => 0,
            'check' => 0,
            'shopping_time' => '9:00-21:00',
            'sid' => getSID(),
            'pay_way' => 0,
            'vip_type' => 0,
            'order_permit' => 0,
            'notice' => ''
        ];
        if ($info['type'] == 2 && $info['member_share'] == 1) {
            $data['info']['show_name'] = 1;
        }
        $configs = ConfigChannel::instance()->where('cid', $cid)->whereIn('code', ['pay_way', 'shopping_vip_type', 'btb_buy', 'b2c_share'])->get()->toArray();
        $configMap = array_column($configs, NULL, 'code');

        //支付方式
        if (!empty($configMap['pay_way']) && !empty($configMap['pay_way']['value'])) {
            $value = json_decode($configMap['pay_way']['value'], true);
            $data['info']['pay_way'] = $value['type'];
        }
        //商场模式
        if (!empty($configMap['shopping_vip_type']) && !empty($configMap['shopping_vip_type']['value'])) {
            $value = json_decode($configMap['shopping_vip_type']['value'], true);
            $data['info']['vip_type'] = $value['vip_type'];
        }
        //是否允许自采
        if (!empty($configMap['btb_buy']) && !empty($configMap['btb_buy']['value'])) {
            $value = json_decode($configMap['btb_buy']['value'], true);
            $data['info']['order_permit'] = $value['buy_type'];
            $data['info']['notice'] = $value['notice'];
        }
        //是否有空中分账
        $data['info']['ledger'] = 0;
        $ledgerInfo = LedgerConfig::instance()->info(['cid' => $cid]);
        if (!empty($ledgerInfo) && $ledgerInfo['switch'] == 1 && $data['info']['pay_way'] == 1) {
            $data['info']['ledger'] = 1;
        }
        $share['vip_title'] = "这张黑卡，真的让你划算到当场失控！";
        $share['vip_desc'] = "拥有这张黑卡，我获得了八项超值特权！";
        $b2c = (!empty($configMap['b2c_share']) && !empty($configMap['b2c_share']['value'])) ? json_decode($configMap['b2c_share']['value'], true) : [];
        $share['store_title'] = $b2c_share['title'] ?? '';
        $share['cover'] = $b2c_share['img'] ?? '';
        $data['vip_share'] = $share;
        return Normal::returnCode(Normal::SUC, '获取成功', $data);
    }

    /**
     * 小店广告模板列表
     * @param int $mnid
     * @param int $cid
     * @param int $mn_sid
     * @param int $mid
     */
    public function storeTemp(int $mnid, int $cid, int $mn_sid, int $mid)
    {
        $checkResult = MnUserService::instance()->checkStore($mnid, $cid, $mn_sid, $mid);
        if ($checkResult['code'] != Normal::SUC) {
            return $checkResult;
        }
        $info = $checkResult['data'];
        $list = Decorate::instance()->lists(['df' => 0, 'cid' => $cid, 'type' => 1, '_fields_' => 'id,name,img,0 as used']);
        foreach ($list as $k => $v) {
            if ($info['adv_temp'] == $v['id']) {
                $list[$k]['used'] = 1;
            }
        }
        return Normal::returnCode(Normal::SUC, '获取成功', $list);
    }

    /**
     * 小店广告模板列表
     * @param int $mnid
     * @param int $temp_id
     * @param int $cid
     * @param int $mn_sid
     * @param int $mid
     */
    public function setStoreTemp(int $mnid, int $temp_id, int $cid, int $mn_sid, int $mid)
    {
        if (empty($temp_id)) {
            return Normal::returnCode(Normal::FAIL, '缺少参数');
        }
        $checkResult = MnUserService::instance()->checkStore($mnid, $cid, $mn_sid, $mid);
        if ($checkResult['code'] != Normal::SUC) {
            return $checkResult;
        }
        $info = $checkResult['data'];
        $temp = Decorate::instance()->info(['cid' => $cid, 'id' => $temp_id]);
        if (empty($temp)) {
            return Normal::returnCode(Normal::FAIL, '该模板不存在');
        }
        Decorate::instance()->startTrans();
        try {
            $tab = DecorateTab::instance()->info([
                'decorate_id' => $temp_id,
                '_order_' => 'show_order asc'
            ]);
            $details = DecorateDetail::instance()->lists(['tab_id' => $tab['id'], 'df' => 0]);
            foreach ($details as $k => $v) {
                if ($v['type'] == 1) {
                    if ($v['object_type'] == 1) { //banner跳转商品
                        //跳转商品,查询小B是否上架此商品
                        MnStoreGoods::instance()->checkGoods(['mn_sid' => $mn_sid, 'goods_id' => $v['object_id'], 'mid' => $mid]);
                    }
                    $insertData[$k]['sid']         = config('STORE_ID');
                    $insertData[$k]['mn_sid']      = $mn_sid;
                    $insertData[$k]['adv_temp']    = $tab['id'];
                    $insertData[$k]['position']    = $v['show_order'];
                    $insertData[$k]['img']         = $v['img_url'];
                    $insertData[$k]['type']        = 1;
                    $insertData[$k]['object_type'] = $v['object_type'];
                    $insertData[$k]['object_id']   = $v['object_id'];
                    $insertData[$k]['activity_id']   = $v['activity_id'];
                    $insertData[$k]['md']          = time();
                }
                if ($v['type'] == 2) { //专题馆
                    $goodsList = SpecialtopicGoods::instance()->where(['specialtopic_id' => $v['object_id'], 'df' => 0])->pluck('goods_id');
                    foreach ($goodsList as $gv) {
                        MnStoreGoods::instance()->checkGoods(['mn_sid' => $mn_sid, 'goods_id' => $gv, 'mid' => $mid]);
                    }
                }
                if ($v['type'] == 3) {
                    $data = json_decode($v['object_id'], true);
                    foreach ($data as $key => $val) {
                        if ($val['object_type'] == 1) { //魔方跳转商品
                            MnStoreGoods::instance()->checkGoods(['mn_sid' => $mn_sid, 'goods_id' => $val['object_id'], 'mid' => $mid]);
                        }
                    }
                }
            }
            Db::table('ly_mn_store_adv')->where('mn_sid', 'eq', $mn_sid)->where('adv_temp', 'neq', $temp_id)->delete(); //删除旧的模板
            if (isset($insertData)) {
                Db::table('ly_mn_store_adv')->insertAll($insertData);
            }
             //黑卡商品处理
             StoreVip::instance()->where(['mn_sid' => $mn_sid])->delete();
             $goods_lists = StoreVip::instance()->where(['mn_sid' => 0, 'adv_temp' => $temp_id])->column('goods_id'); //黑卡商品
             if ($goods_lists) {
                 foreach ($goods_lists as $k => $v) {
                     $insertVipGoods[$k]['sid']      = config('STORE_ID');
                     $insertVipGoods[$k]['cid']      = $cid;
                     $insertVipGoods[$k]['adv_temp'] = $tab['id'];
                     $insertVipGoods[$k]['mn_sid']   = $mn_sid;
                     $insertVipGoods[$k]['goods_id'] = $v;
                     $insertVipGoods[$k]['md']       = time();
                     //跳转商品,查询小B是否上架此商品
                     MnStoreGoods::instance()->checkGoods(['mn_sid' => $mn_sid, 'goods_id' => $v, 'mid' => $mid]);
                 }
                 Db::table('ly_store_vip')->insertAll($insertVipGoods);
             }
             Db::table('ly_mn_user')->where('id', 'eq', $mn_sid)->update(['adv_temp' => $temp_id]);
             Decorate::instance()->commit();
        } catch (\Exception $e) {
            Decorate::instance()->rollback();
            return Normal::returnCode(Normal::FAIL, '模板设置失败' . $e->getMessage());
        }
        return Normal::returnCode(Normal::SUC, '模板设置成功');
    }
}
